import { Request, Response, NextFunction } from 'express';
import * as categoryService from '../models/categoryService'; // 正确导入整个服务模块

// 添加新分类 
export const addCategory = async (req: Request, res: Response) => {
    console.log('req', req.body)
    const { name, parent_id, user_id, family_id } = req.body;
    console.log('name', name)
    console.log('parent_id', parent_id)
    console.log('user_id', user_id)
    console.log('family_id', family_id)
    try {
        // parent_id 可以是 null 或一个有效的数字
        let parsedParentId: number | null = null;
        if (parent_id !== undefined) {
            if (parent_id === null) {
                parsedParentId = null;
            } else {
                parsedParentId = parent_id;
            }
        }
        const newCategoryId = await categoryService.addCategory(name, parsedParentId, user_id, family_id);
        res.status(201).json({ id: newCategoryId, message: '分类创建成功' });
    }
    catch (error) {
        console.error('出错:', error);
        res.status(500).json({
            success: false,
            message: '服务器错误'
        });
    }
};

// 查询所有分类
export const getAllCategories = async (req: Request, res: Response, next: NextFunction) => {
    try {
        const categories = await categoryService.getAllCategories();
        res.json(categories);
    } catch (error) {
        next(error);
    }
}; 

// 查询单个分类详情
export const getCategoryById = async (req: Request, res: Response, next: NextFunction) => {
    try {
        const family_id = parseInt(req.params.family_id);
        const category = await categoryService.getCategoryById(family_id)
        res.json(category);
    } catch (error) {
        console.error('创建作品时出错:', error);
        res.status(500).json({
            success: false,
            message: '服务器错误'
        });
    }
};

// 修改分类
export const updateCategory = async (req: Request, res: Response) => {
    try {
        // const id = parseInt(req.params.id);
        const { name, parent_id, id } = req.body;
        console.log('req.body', req.body)
        let parsedParentId: number | null | undefined = undefined;
        if (parent_id !== undefined) {
            if (parent_id === null) {
                parsedParentId = null;
            } else {
                parsedParentId = parent_id;
            }
        }
        await categoryService.updateCategory(id, name, parsedParentId);
        res.json({ message: '分类更新成功' });
    }
    catch (error) {
        console.error('创建作品时出错:', error);
        res.status(500).json({
            success: false,
            message: '服务器错误'
        });
    }
};

// 删除分类 
export const deleteCategory = async (req: Request, res: Response): Promise<void> => {
    try {
        const { id } = req.body;
        // 验证 id 是否存在
        if (id === undefined || id === null) {
            res.status(400).json({ message: '分类ID不能为空' });
            return;
        }
        // 将 id 转换为数字并验证
        const categoryId = Number(id);
        if (isNaN(categoryId) || categoryId <= 0) {
            res.status(400).json({ message: '分类ID必须是有效的数字' });
            return;
        }
        // 调用服务层删除分类
        await categoryService.deleteCategory(categoryId);

        // 成功删除，返回成功响应
        res.status(200).json({ message: '分类删除成功' });

    } catch (error: any) {
        // 根据错误类型返回不同的响应
        if (error.message === 'Category not found') {
            res.status(404).json({ message: '分类未找到' });
            return;
        }
        if (error.message === 'Cannot delete category with subcategories') {
            res.status(400).json({ message: '无法删除有子分类的分类' });
            return;
        }
        if (error.message === 'Cannot delete category with associated works') {
            res.status(400).json({ message: '无法删除与作品相关联的分类' });
            return;
        }

        // 其他未知错误，返回服务器错误
        console.error('删除分类时出错:', error);
        res.status(500).json({
            success: false,
            message: '服务器错误'
        });
    }
};